/**
 * 
 */
package com.yuri.news.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.yuri.news.entity.Menu;
import com.yuri.news.entity.PrivilegePack;
import com.yuri.news.entity.User;

/**
 * 后端访问拦截
 * @author Yuri
 *
 */
@Component
public class BackInterceptor implements HandlerInterceptor {
	private final Logger logger = LoggerFactory.getLogger(BackInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		try {
			// TODO Auto-generated method stub
			logger.info("\n 后端页面访问拦截 开始");
			// 从session里面获取登录信息
			User user = (User) request.getSession().getAttribute("user");
			logger.info("\n 获取的user：" + user);
			if (user == null) {
				logger.info("\n 用户信息为空 跳转页面");
				response.sendRedirect(request.getContextPath() + "/fore-end/login.html");
				return false;
			}else {
				// 获取用户权限
				PrivilegePack userPack = (PrivilegePack)request.getSession().getAttribute("author");
				logger.info("\n 获取权限信息：userPack = " + userPack);
				// 判断是否有后台权限
				if(userPack != null && userPack.getMenus() != null) {
					Boolean flag = false;
					// 遍历菜单权限
					for(Menu menu : userPack.getMenus()) {
						// 如果有”后台管理权限“
						if("后台管理".equals(menu.getMenuName())) {
							flag = true;
							break;
						}
					}
					// 如果没有"后台管理权限"就跳转到无权限页面
					if(!flag) {
						logger.info("\n 权限不足 跳转页面");
						response.sendRedirect(request.getContextPath() + "/msg.html");
						return false;
					}
					
				}else {
					// 没有就跳转到无权限页面
					response.sendRedirect(request.getContextPath() + "/msg.html");
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
}
